Plotting the derivative function
Plot of area with respect to time
Plot of traingles for different values of roots of the derivative function
An animation to visualise the triangle and its area w.r.t. time
Data generation for this toy problem
A basic linear regression model
Plot of Stock prices over time
Function to calculate daily returns based on moving average window
Covariance matrix of asset returns
Converting the winsorized data to be used with the ZIPLINE trading algorithm
Markovitz Portfolio Optimization
Running Trading Algorithm using Zipline
Plot of the Portfolio value if we start with $100K
Function to throw a dice until the sum exceeds a given threshold
Function to simulate the number of draws needed to exactly match a given threshold
Visualisation for the number of draws needed to exactly hit a given threshold
# !pip install zipline
# !pip install pandas_datareader
# !pip install fix_yahoo_finance
# !pip install cvxopt
# !pip install yahoo-finance
Three points ABC are moving around a unit circle with periods of $1s, 2s$ and $3s$. They all start from the same position on the circle at time $t=0$. Solve for the time and the value when the maximal area of the triangle ABC is reached.
We know that an equilateral triangle has the maximum area if it is inscribed within a circle. Therefore, in this situation at a given time $t$, the vertices of triangle is given by $$\left(cos\left(\frac{2\pi t}{1}\right), sin\left(\frac{2\pi t}{1}\right)\right), \left(cos\left(\frac{2\pi t}{2}\right), sin\left(\frac{2\pi t}{2}\right)\right), \left(cos\left(\frac{2\pi t}{3}\right), sin\left(\frac{2\pi t}{3}\right)\right)$$. If $(x_1,y_1), (x_2, y_2) $ and $(x_3,y_3)$ denote the vertices of a triangle then its area is given by $0.5 \times [(x_2−x_1)(y_3−y_1)−(x_3−x_1)(y_2−y_1)]$. Therefore we have area equal to $$0.5\times \left[ \left(cos\left(\frac{2\pi t}{2} \right)-cos\left(\frac{2\pi t}{1}\right) \right) \left(sin\left(\frac{2\pi t}{3} \right)-sin\left(\frac{2\pi t}{1}\right) \right) - \left(cos\left(\frac{2\pi t}{3} \right)-cos\left(\frac{2\pi t}{1}\right) \right) \left(sin\left(\frac{2\pi t}{2} \right)-sin\left(\frac{2\pi t}{1}\right) \right) \right]$$. Using $$sinA−sinB=2cos((A+B)/2) sin((A−B)/2) \mbox{ and } cosA−cosB=−2sin((A+B)/2) sin((A−B)/2)$$. In order to find the area we find the individual elements in the vertex notation: $$x_2 - x_1 = cos\left(\frac{2\pi t}{2}\right) - cos\left(\frac{2\pi t}{1}\right) = 2sin\left(2\pi t\frac{3}{4} \right) sin\left(2\pi t\frac{1}{4} \right),$$ $$y_3 - y_1 = sin\left(\frac{2\pi t}{3}\right) - sin\left(\frac{2\pi t}{1}\right) = -2cos\left(2\pi t\frac{4}{6} \right) sin\left(2\pi t\frac{2}{6} \right),$$ $$x_3 - x_1 = cos\left(\frac{2\pi t}{3}\right) - cos\left(\frac{2\pi t}{1}\right) = 2sin\left(2\pi t\frac{4}{6} \right) sin\left(2\pi t\frac{2}{6} \right),$$ $$y_2 - y_1 = sin\left(\frac{2\pi t}{2}\right) - sin\left(\frac{2\pi t}{1}\right) = -2cos\left(2\pi t\frac{3}{4} \right) sin\left(2\pi t\frac{1}{4} \right).$$ Therefore, the area at time $t$ is given by:
$$2A(t) = -4 sin\left(2\pi t\frac{1}{4} \right)sin\left(2\pi t\frac{2}{6} \right)\left[ sin\left(2\pi t\frac{3}{4} \right) cos\left(2\pi t\frac{4}{6} \right) - sin\left(2\pi t\frac{4}{6} \right) cos\left(2\pi t\frac{3}{4} \right)\right] \\ = -4 sin\left(2\pi t\frac{1}{4} \right)sin\left(2\pi t\frac{1}{3} \right) sin\left(2\pi t\frac{1}{12} \right) \\ =\frac{-4}{2} \left[ cos\left(2\pi t\frac{1}{12}\right) - cos\left(2\pi t\frac{7}{12} \right) \right] sin\left(2\pi t\frac{1}{12} \right) \\ = -2 cos\left(2\pi t\frac{1}{12} \right) sin\left(2\pi t\frac{1}{12} \right) + 2 cos\left(2\pi t\frac{7}{12} \right) sin\left(2\pi t\frac{1}{12} \right) \\ = -sin\left(2\pi t\frac{1}{6} \right) + \frac{2}{2} \left[ sin\left(2\pi t\frac{8}{12} \right) - sin\left(2\pi t\frac{1}{12} \right) \right].$$
In order to find the maximum area, we find the derivative of $A(t)$ w.r.t $t$ which yeilds:
$$\frac{dA(t)}{dt} = -\frac{2\pi}{6}cos\left(2\pi t\frac{1}{6} \right) + \frac{4\pi}{3}cos\left(2\pi t\frac{2}{3} \right) - \frac{2\pi}{2}cos\left(2\pi t\frac{1}{2} \right) = 0 \\ = -\frac{1}{3}cos\left(2\pi t\frac{1}{6} \right) + \frac{4}{3}cos\left(2\pi t\frac{2}{3} \right) - cos\left(2\pi t\frac{1}{2} \right) = 0.$$
We would numerically solve this equation and find its roots which follows below.
def derivative_function(t):
"""
Derivative function of the area, upto a constant
"""
res = -np.cos(2*np.pi*t/6)/3 + 4*np.cos(4*np.pi*t/3)/3 - np.cos(np.pi*t)
return res
t = np.linspace(0, 10, 1000)
y = range(len(t))
for i in range(len(t)):
y[i] = derivative_function(t[i])
%matplotlib inline
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')
plt.plot(t,y, 'r')
plt.xlabel('Time')
plt.ylabel('Derivative')
# finding the roots of the derivative function
from scipy import optimize
all_roots = range(10)
for i in range(len(all_roots)):
all_roots[i] = optimize.brenth(derivative_function, i+0.1, i+1)
print all_roots
We could simply find the second derivative and check if the second derivative is negative to find local maxima. Therefore, I have written a python function below which simply finds the area of the triangle at the given time instance. And hence we can pick where the maxima occurs. I have also plotted the area of triangle with respect to the time. The time instance where the maxima occurs are $t = 2.5451617144182412, 3.4548382855816904, 8.54516171441824, 9.45483828558169,...$. I have concluded this based on the behavior of the the area with respect to time variable, which is given in visualisation that follows below:
%matplotlib inline
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')
def polar_coordinate(t, period):
"""
Function returns the polar co-ordinate of a point at time t which moves
around a circle of radius 1 with period equal to "period"
"""
res = [np.cos(2*np.pi*t/period), np.sin(2*np.pi*t/period)]
return res
def vertex_of_triangle_at_time(t, periods = [1,2,3]):
"""
Function returns the co-ordinates of all three vertices of a triangle
where the vertices are given by the position of three particles moving
with different periods, at a given time instance.
"""
res = [polar_coordinate(t, periods[0]),
polar_coordinate(t, periods[1]),
polar_coordinate(t, periods[2])]
return res
def area_of_triangle_at_time(t):
"""
Function returns the area of triangle at a given instance t
"""
# find the vertices of traingle
v = vertex_of_triangle_at_time(t)
# extract all x and y components
x = [v[0][0], v[1][0], v[2][0]]
y = [v[0][1], v[1][1], v[2][1]]
# calculate the area
area = abs(0.5*((x[1] - x[0])*(y[2]-y[0]) - (x[2] - x[0])*(y[1] - y[0])))
return area
def draw_triangle_inside_circle(t):
"""
A visualisation to see the positions of all the three particles around the
circle of radius 1 which moves with different periods.
"""
circle = plt.Circle((0.0, 0.0), 1, color='blue')
fig = plt.gcf()
fig.set_size_inches(6, 6)
plt.gcf().gca().add_artist(circle)
plt.xlim(-1.2,1.2)
plt.ylim(-1.2,1.2)
v = vertex_of_triangle_at_time(t)
x = [v[0][0], v[1][0], v[2][0], v[0][0]]
y = [v[0][1], v[1][1], v[2][1], v[0][1]]
for i in range(3):
plt.plot(x[i:i+2], y[i:i+2], 'ro-')
leg = "Area is: %2f"%area_of_triangle_at_time(t)
#print leg
plt.text(-1,1, leg, color = 'red')
import numpy as np
def plot_area_vs_time(t = np.linspace(-10, 10, 1000)):
y = range(len(t))
for i in range(len(t)):
y[i] = area_of_triangle_at_time(t[i])
plt.plot(t, y)
plt.xlabel('Time')
plt.ylabel('Area')
plot_area_vs_time(np.linspace(0,16,1000))
# plot the positions of three particles
jet= plt.get_cmap('jet')
colors = iter(jet(np.linspace(0,1,10)))
for i in range(len(all_roots)):
plt.figure()
draw_triangle_inside_circle(all_roots[i])
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation, rc
from IPython.display import HTML
# animate over some set of x, y
patch = plt.Circle((0, 0), 1, fc='y')
# First set up the figure, the axes, and the plot element
fig, ax = plt.subplots()
fig.set_size_inches(6, 6)
plt.close()
ax.set_xlim(( -1.2, 1.2))
ax.set_ylim((-1.2, 1.2))
line1, = ax.plot([], [], lw=2, color = 'red')
line2, = ax.plot([], [], lw=2, color = 'red')
line3, = ax.plot([], [], lw=2, color = 'red')
time_text = ax.text(-1, 1, '', color = 'red')
area_text = ax.text(0.5,1, '', color = 'red')
pt1 = ax.text([],[],'', color = 'black', fontsize = 'x-large')
pt2 = ax.text([],[],'', color = 'black', fontsize = 'x-large')
pt3 = ax.text([],[],'', color = 'black', fontsize = 'x-large')
# initialization function: plot the background of each frame
def init():
patch.center = (0, 0)
ax.add_patch(patch)
return (patch,)
# animation function: this is called sequentially
def animate(i):
t = 0.01*i
v = vertex_of_triangle_at_time(t)
x = [v[0][0], v[1][0], v[2][0], v[0][0]]
y = [v[0][1], v[1][1], v[2][1], v[0][1]]
line1.set_data([x[0],x[1],x[1],x[2],x[2],x[0]], [y[0],y[1],y[1],y[2],y[2],y[0]])
area_txt = "Area : %2f"%area_of_triangle_at_time(t)
time_txt = "Time : %2f"%t
time_text.set_text(time_txt)
area_text.set_text(area_txt)
pt1.set_text('1')
pt1.set_x(x[0])
pt1.set_y(y[0])
pt2.set_text('2')
pt2.set_x(x[1])
pt2.set_y(y[1])
pt3.set_text('3')
pt3.set_x(x[2])
pt3.set_y(y[2])
return (line1,time_text,area_text,)
anim = animation.FuncAnimation(fig, animate, init_func=init, frames=350, interval=100, blit=False)
rc('animation', html='jshtml')
anim